package com.shanhai.wallpapers.fragments.wallpapers

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.core.view.isVisible
import androidx.paging.LoadState
import androidx.paging.LoadStateAdapter
import androidx.recyclerview.widget.RecyclerView
import com.shanhai.wallpapers.databinding.ItemLoadErrorStateBinding

class PexelsLoadStateAdapter(private val retry: () -> Unit) :
    LoadStateAdapter<PexelsLoadStateAdapter.LoadStateViewHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, loadState: LoadState): LoadStateViewHolder {
        return LoadStateViewHolder(
            ItemLoadErrorStateBinding.inflate(
                LayoutInflater.from(parent.context),
                parent,
                false
            )
        )
    }

    override fun onBindViewHolder(holder: LoadStateViewHolder, loadState: LoadState) {
        holder.bind(loadState)
    }


    inner class LoadStateViewHolder(
        private val binding: ItemLoadErrorStateBinding
    ) : RecyclerView.ViewHolder(binding.root) {
        init {
            binding.buttonRetry.setOnClickListener { retry.invoke() }
        }

        fun bind(loadState: LoadState) {
            with(binding) {
                if (loadState is LoadState.Error) {
                    textError.text = loadState.error.message
                    progressBar.isVisible = false
                    textError.isVisible = true
                    buttonRetry.isVisible = true
                } else {
                    textError.isVisible = false
                    progressBar.isVisible = true
                    buttonRetry.isVisible = false
                }
            }
        }
    }
}